<script setup>
import {onMounted, ref} from 'vue';
import InstallButton from './components/InstallButton.vue';
import LoadingOverlay from './components/LoadingOverlay.vue';
import api from './api'

// 添加进度条状态
const isInstalling = ref(false);
const installProgress = ref(0);

onMounted(async () => {
  await getAppInfo();
  
  // 监听PWA安装提示事件
  window.addEventListener('beforeinstallprompt', (event) => {
    console.log('🎉 PWA install prompt available!');
    console.log('beforeinstallprompt event:', event);
    event.preventDefault();
    window.deferredPrompt = event;
    console.log('deferredPrompt saved:', window.deferredPrompt);
  });
  
  // 添加页面加载完成后的检查
  window.addEventListener('load', () => {
    console.log('Page loaded, checking PWA conditions...');
    console.log('Service Worker registered:', navigator.serviceWorker.controller ? 'Yes' : 'No');
    console.log('Manifest link exists:', document.querySelector('link[rel="manifest"]') ? 'Yes' : 'No');
    console.log('Is secure context:', window.isSecureContext);
  });
  
  // 监听PWA安装完成事件
  window.addEventListener('appinstalled', () => {
    console.log('PWA was installed successfully');
    window.deferredPrompt = null;
  });
  
  // 设置视口高度，解决移动端100vh问题
  const setViewportHeight = () => {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
    
    // 调整容器高度
    const header = document.querySelector('.distribute-header');
    const content = document.querySelector('.distribute-content');
    if (header && content) {
      const headerHeight = header.offsetHeight;
      content.style.height = `calc(100% - ${headerHeight}px)`;
    }
  };
  
  setViewportHeight();
  window.addEventListener('resize', setViewportHeight);
  
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('/service-worker.js')
        .then((registration) => {
          console.log('Service Worker registered successfully:', registration.scope);
          // 检查是否有更新
          registration.addEventListener('updatefound', () => {
            console.log('Service Worker update found');
          });
        })
        .catch((error) => console.error('Service Worker registration failed:', error));
  }

  if (window.matchMedia('(display-mode: standalone)').matches) {
    console.log('App Mode (PWA)');
    window.location.href = "/go.html";
  } else {
    console.log('Browser Mode');
  }
});

async function getAppInfo() {
  try {
    const res = await api.getAppInfo()
    appInfo.value = JSON.parse(res.data.data.data)
  } catch (e) {
    console.log(e)
  }
}

const descriptions = ref([
  'No data shared with third parties Learn more about how developers declare sharing',
  'This app may collect these data types Location, App activity and 2 others',
  'Data is encrypted in transit',
  'You can request that data be deleted'
]);
// 在script setup中导入图标
import icDataShare from '@/assets/ic_data_share.svg'
import icCloudUpload from '@/assets/ic_cloud_upload.svg'
import icLock from '@/assets/ic_lock.svg'
import icDelete from '@/assets/ic_delete.svg'

const icons = ref([
  icDataShare,
  icCloudUpload,
  icLock,
  icDelete
]);

const appInfo = ref({
  name: '',
  version: '',
  apkPath: '',
  icon: '',
  fileSize: '',
  updateTime: ''
})

const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const mb = bytes / (1024 * 1024)
  if (mb >= 1) {
    return `${mb.toFixed(1)} MB`
  }
  const kb = bytes / 1024
  return `${kb.toFixed(1)} KB`
}

// 检测是否为移动设备
const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

// 检测是否为Android设备
const isAndroid = () => {
  return /Android/i.test(navigator.userAgent);
}

// 进度条动画函数
const animateProgress = () => {
  return new Promise((resolve) => {
    installProgress.value = 0;
    const duration = 6000; // 6秒完成
    const interval = 80; // 每80ms更新一次
    const increment = (interval / duration) * 100;
    
    const timer = setInterval(() => {
      installProgress.value += increment;
      
      if (installProgress.value >= 100) {
        installProgress.value = 100;
        clearInterval(timer);
        setTimeout(() => {
          resolve();
        }, 300); // 稍微延迟一下让用户看到100%
      }
    }, interval);
  });
};

const downloadApk = async () => {
  console.log('Download button clicked');
  console.log('window.deferredPrompt:', window.deferredPrompt);
  console.log('Service Worker support:', 'serviceWorker' in navigator);
  console.log('Current URL:', window.location.href);
  console.log('Is HTTPS:', window.location.protocol === 'https:');
  console.log('Display mode:', window.matchMedia('(display-mode: standalone)').matches ? 'standalone' : 'browser');
  
  // 防止重复点击
  if (isInstalling.value) {
    return;
  }
  
  // 开始安装流程
  isInstalling.value = true;
  
  try {
    // 检查是否支持PWA安装
    if (window.deferredPrompt) {
      console.log('PWA install prompt available, showing prompt...');
      
      // 开始进度条动画
      const progressPromise = animateProgress();
      
      // 显示安装提示
      await window.deferredPrompt.prompt();
      
      // 等待用户选择
      const { outcome } = await window.deferredPrompt.userChoice;
      
      // 等待进度条完成
      await progressPromise;
      
      if (outcome === 'accepted') {
        console.log('User accepted the PWA install prompt');
        // alert('应用安装成功！您可以在桌面或应用列表中找到它。');
      } else {
        console.log('User dismissed the PWA install prompt');
        // alert('您取消了安装。如需安装，请重新点击下载按钮。');
      }
      
      // 清除deferredPrompt
      window.deferredPrompt = null;
    } else {
      console.log('PWA install prompt not available');
      
      // 即使没有PWA提示，也显示进度条给用户反馈
      await animateProgress();
      
      // 检查是否已经安装
      if (window.matchMedia('(display-mode: standalone)').matches) {
        // alert('应用已经安装！');
      } else {
        // 提供手动安装指导
        // alert('请在浏览器菜单中选择"添加到主屏幕"或"安装应用"来安装此PWA应用。\n\n支持的浏览器：Chrome、Edge、Safari等。');
      }
    }
  } catch (error) {
    console.error('PWA installation failed:', error);
    // alert('安装失败，请稍后重试。');
  } finally {
    // 重置状态
    setTimeout(() => {
      isInstalling.value = false;
      installProgress.value = 0;
    }, 500);
  }
}

// 移除了APK下载相关的辅助函数
</script>

<template>
  <div class="app-container">
    <!-- 顶部背景区域 -->
    <div class="top-header-section">
      <div class="distribute-bg-container"></div>
    </div>
    
    <!-- 彩色渐变背景 -->
    <!-- <div class="gradient-background">
      <div class="gradient-shape gradient-shape-1"></div>
      <div class="gradient-shape gradient-shape-2"></div>
      <div class="gradient-shape gradient-shape-3"></div>
      <div class="gradient-shape gradient-shape-4"></div>
    </div> -->
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 应用图标区域 -->
      <div class="app-icon-section">
        <div class="app-icon-container">
          <div class="app-icon-wrapper">
            <img :src="appInfo.icon || '/favicon.ico'" alt="App Icon" class="app-icon">
          </div>
        </div>
      </div>
      
      <!-- 应用信息 -->
      <div class="app-info-section">
        <img src="@/assets/name.png" alt="App Name" class="app-name-image">
        <div class="app-meta">
          <span class="version">version: {{ appInfo.version || '1.0.1' }} size: {{ formatFileSize(appInfo.fileSize || '5110000') }}</span>
          <span class="update-time">Update time: {{ formatDate(appInfo.updateTime || '2025-01-22 17:17:21') }}</span>
        </div>
      </div>
      
      <!-- 下载按钮 -->
      <div class="download-section">
        <button class="download-btn" @click="downloadApk" :disabled="isInstalling">
          <div class="download-btn-content">
            <span class="download-text" v-if="!isInstalling">Download the app</span>
            <span class="download-text" v-else>Installing... {{ Math.round(installProgress) }}%</span>
          </div>
          <div class="progress-bar" v-if="isInstalling">
            <div class="progress-fill" :style="{ width: installProgress + '%' }"></div>
          </div>
        </button>
        <p class="platform-info">For Android</p>
      </div>
      
      <!-- 数据安全部分 -->
      <div class="data-safety-section">
        <div class="section-header">
          <h2 class="section-title">Data safety</h2>
          <div class="arrow-icon">→</div>
        </div>
        
        <div class="safety-description">
          <p>
            Safety starts with understanding how developers collect and share your data. 
            Data privacy and security practices may vary based on your use, region, and age. 
            The developer provided this information and may update it over time.
          </p>
        </div>

        <div class="safety-features">
          <div v-for="(desc, index) in descriptions" :key="index" class="safety-item">
            <div class="safety-icon">
              <img :src="icons[index]" alt="Safety icon" class="icon-svg">
            </div>
            <div class="safety-text">
              {{ desc }}
            </div>
          </div>
        </div>
      </div>
   
    </div>
  </div>

  <div class="shdow" id="mask">
    <img id="mask-tip">
  </div>

  <LoadingOverlay/>
</template>

<style scoped>
.app-container {
  min-height: 100vh;
  height: auto;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部背景区域 */
.top-header-section {
  position: relative;
  width: 100%;
  height: 150px;
  z-index: 1;
}

.distribute-bg-container {
  width: 100%;
  height: 100%;
  background: url('./assets/distribute-bg.png') center/cover no-repeat;
  background-size: cover;
}

.app-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(229, 219, 219, 0.1);
  z-index: 0;
}


/* 主要内容 */
.main-content {
  position: relative;
  z-index: 2;
  margin-top: -160px;
  width: 100%;
  height: auto;
  padding-bottom: 40px;
}

/* 应用图标区域 */
.app-icon-section {
  display: flex;
  justify-content: center;
  margin-bottom: 12px;
}

.app-icon-container {
  position: relative;
}

.app-icon-wrapper {
  width: 210px;
  height: 210px;
  background: white;
  border-radius: 25px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  display: flex;
  align-items: center;
  justify-content: center;
}

.app-icon {
  width: 120px;
  height: 120px;
  border-radius: 25px;
  object-fit: cover;
}

/* 应用信息 */
.app-info-section {
  text-align: center;
  margin-bottom: 20px;
}

.app-name {
  font-size: 32px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.app-name-image {
  max-width: 120px;
  height: auto;
  margin: 0 0 8px 0;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.app-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 8px;
  color: #666;
}

/* 下载按钮 */
.download-section {
  margin-bottom: 32px;
  padding: 0 10px;
}

.download-btn {
  width: 100%;
  height: 42px;
  background: linear-gradient(135deg, #00d4aa 0%, #00b894 100%);
  border: none;
  border-radius: 28px;
  color: white;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(0, 212, 170, 0.3);
  margin-bottom: 8px;
}

.download-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 212, 170, 0.4);
}

.download-btn:active {
  transform: translateY(0);
}

.platform-info {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin: 0;
}

/* 数据安全部分 */
.data-safety-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  position: relative;
}

.section-title {
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.arrow-icon {
  font-size: 20px;
  color: #666;
  position: absolute;
  right: 0;
}

.safety-description {
  margin-bottom: 12px;
}

.safety-description p {
  font-size: 15px;
  line-height: 1.5;
  color: #666;
  margin: 0;
}

.safety-features {
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
}

.safety-item {
  display: flex;
  align-items: flex-start;
  padding: 8px;
  border-bottom: 1px solid #e9ecef;
}

.safety-item:last-child {
  border-bottom: none;
}

.safety-icon {
  width: 24px;
  height: 24px;
  margin-right: 16px;
  flex-shrink: 0;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-svg {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.safety-text {
  flex: 1;
  font-size: 15px;
  line-height: 1.4;
  color: #333;
}

/* 额外内容区域 */
/* .additional-content { */
  /* padding: 0 20px; */
/* } */

/* .content-spacer { */
  /* height: 40px; */
/* } */

/* 应用详情部分 */
.app-details-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.details-title {
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 16px 0;
}

.details-content p {
  font-size: 15px;
  line-height: 1.6;
  color: #666;
  margin: 0 0 12px 0;
}

.details-content p:last-child {
  margin-bottom: 0;
}

/* 评分和评论部分 */
.rating-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.rating-title {
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 16px 0;
}

.rating-summary {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rating-score {
  font-size: 48px;
  font-weight: 700;
  color: #1a1a1a;
}

.rating-stars {
  font-size: 20px;
  color: #ffc107;
}

.rating-count {
  font-size: 14px;
  color: #666;
}

.bottom-spacer {
  height: 80px;
}

.learn-more {
  display: block;
  color: #007bff;
  margin-top: 4px;
  cursor: pointer;
  font-size: 14px;
}

.learn-more:hover {
  text-decoration: underline;
}

.shdow {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 1000;
}

#mask-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 80%;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .main-content {
    padding-top: 40px;
    padding-bottom: 20px;
  }
  
  .app-icon-section {
    padding: 0 16px;
  }
  
  .app-info-section {
    padding: 0 16px;
  }
  
  .download-section {
    padding: 0 16px;
  }
  
  .data-safety-section {
    margin: 0 16px;
    padding: 20px 16px;
  }
  
  .app-icon-wrapper {
    width: 100px;
    height: 100px;
  }
  
  .app-name {
    font-size: 28px;
  }
  
  .app-meta {
    font-size: 14px;
  }
  
  .download-btn {
    height: 50px;
    font-size: 16px;
  }
}

/* 全局样式重置 */
:global(html), :global(body) {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

:global(#app) {
  width: 100%;
  height: 100%;
  overflow: auto;
}
</style>

 
